package com.aifast.system.sys.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.base.Controller;
import com.aifast.common.base.R;
import com.aifast.common.cache.util.RedisUtil;
import com.aifast.common.global.BusinessException;
import com.aifast.common.global.Const;
import com.aifast.common.global.Status;
import com.aifast.system.log.service.LogLoginService;
import com.aifast.system.sys.entity.UserInfo;
import com.aifast.system.sys.service.StpInterfaceService;
import com.aifast.system.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @Author fujian
 * @since 2022/1/14 10:23
 *  登录
 */
@RequiredArgsConstructor
@RequestMapping("login")
@RestController
public class LoginController extends Controller {

    private final SysUserService service;
    private final StpInterfaceService stpInterfaceService;
    private final LogLoginService logLoginService;

    @GetMapping("getCaptcha")
    public void getCaptcha() throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(144, 70, 4, 20);
        String key = StrUtil.join(Const.SYMBOL_COLON, "login", request.getSession().getId());
        RedisUtil.set(key, captcha.getCode(), 60 * 5);
        captcha.write(response.getOutputStream());
    }

    @PostMapping("go")
    public SaResult go(){
        return service.login(get("username"),get("password"),get("code"),request.getSession().getId(),request);
    }

    @GetMapping("out")
    public R out(){
        Integer loginId = Convert.toInt(StpUtil.getLoginId());
        if(ObjectUtil.isNull(loginId)){
            throw  new BusinessException("loginId不能为空");
        }

        logLoginService.putLogout(UserInfo.get(loginId.toString()),request);
        UserInfo.remove(Convert.toStr(loginId.toString()));
        StpUtil.logout(loginId,Const.PC);
        return R.ERROR(Status.LOGOUT);
    }

    @GetMapping("isLogin")
    public R isLogin(){
//        sa-token判断是根据浏览器会话即session的判断 这里要加上自定义缓存的判断
//        return (StpUtil.isLogin() || ObjectUtil.isNotNull(UserInfo.get())) ? OK() : ERROR();
        return StpUtil.isLogin() ? OK() : ERROR();
    }

}
